/**
 * 
 */
package cn.gov.msa.ws;

import java.io.File;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.context.ApplicationContext;

import com.github.pagehelper.PageInfo;

import cn.gov.msa.dao.RecordCompanyMapper;
import cn.gov.msa.model.Amanuensis;
import cn.gov.msa.model.Apply;
import cn.gov.msa.model.DeclareItemMaterial;
import cn.gov.msa.model.NavigationMark;
import cn.gov.msa.model.RecordCompany;
import cn.gov.msa.model.VSelectBusinessQuery;
import cn.gov.msa.model.Waterway;
import cn.gov.msa.service.ApplyService;
import cn.gov.msa.service.QueryService;
import cn.gov.msa.service.WaterwayService;
import cn.gov.msa.util.AmanuensisThread;
import cn.gov.msa.util.FileUtil;
import cn.gov.msa.util.InfoObjUtil;
import cn.gov.msa.util.PropertiesTools;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**   
* @Title: DictService.java 
* @Package cn.gov.msa.ws 
* @Description: TODO(用一句话描述该文件做什么) 
* @author 何宇江  
* @date 2018年3月12日 上午10:08:56 
*/
public class BusinessService {
    private static String path = PropertiesTools.readProperties("project.path") ;
	/*
	 * 业务保存服务
	 * */
	public static String saveData(ApplicationContext ctx, String params) throws Exception {int result = 0;
		String info = InfoObjUtil.Error_save_no;
	    JSONObject jsonResult = new JSONObject();
		ExecutorService  singleThread = Executors.newSingleThreadExecutor();
		try{
			boolean issubmit = JSONObject.fromObject(params).getBoolean("issubmit");
			
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");  

	        JSONObject jsonUser = JSONObject.fromObject(params).getJSONObject("user");
			JSONObject jsonApply = JSONObject.fromObject(params).getJSONObject("Apply");
			JSONObject jsonBusiness = JSONObject.fromObject(params).getJSONObject("Business");
			JSONArray jaMaterial = JSONObject.fromObject(params).optJSONArray("Material");
			JSONArray jaVerify = JSONObject.fromObject(params).optJSONArray("Verify");
			
			JSONArray jaShip = new JSONArray();
			if(JSONObject.fromObject(params).has("Ship")) 
				jaShip = JSONObject.fromObject(params).getJSONArray("Ship");
			
			JSONArray jaCoordinate = new JSONArray();
			if(JSONObject.fromObject(params).has("Coordinate")) 
				jaCoordinate = JSONObject.fromObject(params).getJSONArray("Coordinate");
			
			// 设备及主要技术参数
			JSONArray jaDevice = new JSONArray();
			if(JSONObject.fromObject(params).has("Device")) 
				jaDevice = JSONObject.fromObject(params).getJSONArray("Device");

			jsonApply.put("company", jsonUser.getString("company"));
			jsonApply.put("companyid", jsonUser.getString("companyid"));
			jsonApply.put("contactaddr", jsonUser.optString("contactaddr"));
			jsonApply.put("email", jsonUser.optString("email"));
			jsonApply.put("mobilephone", jsonUser.optString("mobilephone"));
			jsonApply.put("proposer", jsonUser.getString("proposer"));
			jsonApply.put("proposerid", jsonUser.getString("proposerid"));
			jsonApply.put("telephone", jsonUser.optString("telephone"));
			
			String applyno = "";
			
			RecordCompany recordCompany = new RecordCompany(); //检查是否已经备案（条件：公司编号、海事机构）
			recordCompany.setOrgcode(jsonApply.getString("orgcode"));
			recordCompany.setCompanyid(jsonApply.getString("companyid"));
			
			if(jsonApply.getString("itemno").equals("10001")){
				List<RecordCompany> recordCompanyList = applyService.selectCompany(recordCompany);
				if(recordCompanyList.size() > 0 && jsonBusiness.optString("recordid").equals("")){
					result = 0;
					info = "您已经在【" + jsonApply.getString("orgname") + "】已经申报备案，不可以重复申报！";
				}
				else{
					jsonBusiness.put("userid", jsonUser.optString("proposerId"));
					jsonBusiness.put("username", jsonUser.optString("proposer"));
					applyno = applyService.saveData(jsonApply, jsonBusiness, jaMaterial, jaShip, jaCoordinate, jaVerify, jaDevice, issubmit);
				}
			}
			else{
				recordCompany.setState(1);
				List<RecordCompany> recordCompanyList = applyService.selectCompany(recordCompany);
				if(recordCompanyList.size() == 0 || recordCompanyList.get(0).getState() == 0){
					result = 0;
					info = "您还未在【" + jsonApply.getString("orgname") + "】申请备案，不能进行业务申报！";
				}
				else{
					applyno = applyService.saveData(jsonApply, jsonBusiness, jaMaterial, jaShip, jaCoordinate, jaVerify, jaDevice, issubmit);
				}
			}
			
	        if("" != applyno){
	        	result = 1;
	        	info = InfoObjUtil.Success_save_OK; 
	        	
	        	JSONObject jsonApplyResult = new JSONObject();
	        	jsonApplyResult.put("applyno", applyno);
	        	jsonResult.put("datas", jsonApplyResult);
	        	
	        	singleThread.execute(new AmanuensisThread(applyno,applyService));
	        	 
	        	//保存文书
//	        	applyService.saveAmanuensis(applyno);
	        }
		}
		catch(Exception e){
			if(!singleThread.isTerminated()) {
				singleThread.shutdownNow();
			}
			e.printStackTrace();
        	result = 2;
        	info = e.toString();
		}finally{
			singleThread.shutdown();
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	/*
	 * 获取业务的提交材料列表
	 * */
	public static String getMaterial(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");  
	         
	        String itemno = JSONObject.fromObject(params).getString("itemno");
	        List<DeclareItemMaterial>  declareItemMaterialList = applyService.getMaterial(itemno);
	        
	        if(declareItemMaterialList.size() > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;

	        	jsonResult.put("datas", declareItemMaterialList);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}


	public static String  selectData(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
			JSONObject param = JSONObject.fromObject(params);
//			QueryService queryService = (QueryService) ctx.getBean("QueryService");  
			ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");  
	         
			int pageNum = 1;
			int pageSize = 10;
			if(param.has("pageNum"))
			{
				pageNum = param.getInt("pageNum");
				param.remove("pageNum");
			}
			if(param.has("pageSize"))
			{
				pageSize = param.getInt("pageSize");
				param.remove("pageSize");
			}

//			VSelectBusinessQuery vSelectBusinessQuery = (VSelectBusinessQuery)JSONObject.toBean(param, VSelectBusinessQuery.class);
//			
//			List<VSelectBusinessQuery> vSelectBusinessQueryList = queryService.selectData(pageNum, pageSize, vSelectBusinessQuery);
//		    //获取分页信息
//	        PageInfo page = new PageInfo(vSelectBusinessQueryList);
			

			Apply apply = (Apply)JSONObject.toBean(param, Apply.class);
			List<Apply> applyList = applyService.selectData(pageNum, pageSize, apply);
			// 获取分页信息
			PageInfo page = new PageInfo(applyList);
	        
	        if(applyList.size() > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;
	        	
	        	JSONObject datas = new JSONObject();
	        	datas.put("total", page.getTotal());
	        	datas.put("rows", applyList);

	        	jsonResult.put("datas", datas);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	
	

	public static String getDetail(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	    	String applyno = jsonParams.getString("applyno");

	    	String datas = applyService.getInfo(applyno);
	        
	        if(datas != null){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;

	        	jsonResult.put("datas", datas);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	public static String deleteapply(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_save_no;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	    	String applyid = jsonParams.getString("applyid");

	    	int iDelete = applyService.deelteApply(applyid);
	        
	        if(iDelete > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_save_OK;
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}

	public static String selectCorrection(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	    	String applyno = jsonParams.getString("applyno");

	    	String datas = applyService.getCorrectionInfo(applyno);
	        
	        if(datas != null){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;

	        	jsonResult.put("datas", datas);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}

	public static String amanuensis(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	    	String applyid = jsonParams.getString("applyid");

			Amanuensis amanuensis = new Amanuensis();
			amanuensis.setApplyid(applyid);
			
	    	List<Amanuensis> amanuensisList = applyService.getAmanuensis(amanuensis);
	    	JSONArray jaResult = new JSONArray();
	    	for (Amanuensis amanuensis1 : amanuensisList) {
				JSONObject jsonAmanuensis = JSONObject.fromObject(amanuensis1);
				
		    	File f = new File(path + amanuensis1.getFileurl());
		    	
//		    	String filecontent = FileUtil.bytesToHexString(FileUtil.fileTobyte(f));
//		    	
//		    	jsonAmanuensis.put("filecontent", filecontent);
		    	
				
				jaResult.add(jsonAmanuensis);
			}
	        
	        if(amanuensisList.size() > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;

	        	jsonResult.put("datas", jaResult);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	public static String amanuensisbyid(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);
	        
	        String amanuensisid = jsonParams.getString("amanuensisid");

	        Amanuensis amanuensis = applyService.getAmanuensisById(amanuensisid);
	        JSONObject jsonDatas = JSONObject.fromObject(amanuensis);
			
	        
	        if(amanuensis!=null){
		    	String filecontent = FileUtil.bytesToHexString(amanuensis.getAttachment());
		    	jsonDatas.put("filecontent", filecontent);
		    	
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;

	        	jsonResult.put("datas", jsonDatas.toString());
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	public static String waterwayData(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        WaterwayService waterwayService = (WaterwayService) ctx.getBean("WaterwayService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);

	        Waterway waterway = new Waterway();
	        waterway.setOrgcode(jsonParams.getString("orgcode"));

	        List<Waterway> waterwayList = waterwayService.getWaterwayList(waterway);
			
	        if(waterwayList.size() > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;
	        	jsonResult.put("datas", waterwayList);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	

	public static String markData(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        WaterwayService waterwayService = (WaterwayService) ctx.getBean("WaterwayService");
	        
	        JSONObject jsonParams = JSONObject.fromObject(params);

	        NavigationMark navigationMark = new NavigationMark();
	        navigationMark.setWaterwaycode(jsonParams.getString("waterwaycode"));

	        List<NavigationMark> navigationMarkList = waterwayService.getMarkList(navigationMark);
			
	        if(navigationMarkList.size() > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_select_OK;
	        	jsonResult.put("datas", navigationMarkList);
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	
	/*
	 * 业务申报评价
	 * */
	public static String saveComment(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_save_no;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
	        Apply apply = (Apply)JSONObject.toBean(JSONObject.fromObject(params), Apply.class);
	        int i = applyService.saveComment(apply);
	        
	        if(i > 0){
	        	result = 1;
	        	info = InfoObjUtil.Success_save_OK;
	        }
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
	


	public static String selectCompanyOrg(ApplicationContext ctx, String params) throws Exception {
		int result = 0;
		String info = InfoObjUtil.Error_NODATA;
	    JSONObject jsonResult = new JSONObject();
		
		try{
	        ApplyService applyService = (ApplyService) ctx.getBean("ApplyService");
	        
			JSONObject jsonParams = JSONObject.fromObject(params);
			
			String companyid = jsonParams.getString("companyid");
			
			RecordCompany recordCompany = new RecordCompany(); //检查是否已经备案（条件：公司编号、海事机构）
			recordCompany.setCompanyid(companyid);
//			recordCompany.setState(1);
			recordCompany.setState(-1);
			List<RecordCompany> recordCompanyList = applyService.selectCompany(recordCompany);
			
			if(recordCompanyList.size() > 0){
				result = 1;
				info = InfoObjUtil.Success_save_OK;
				
				jsonResult.put("datas", recordCompanyList);
			}
		}
		catch(Exception e){
			e.printStackTrace();
        	result = 2;
        	info = InfoObjUtil.Exption_msg;
		}
		

    	jsonResult.put("result", result);
    	jsonResult.put("info", info);

		
		return jsonResult.toString();
	}
}
